package cn.xshi.sys.web;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import cn.xshi.common.base.*;
import cn.xshi.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.xshi.common.annotation.Auth;
import cn.xshi.common.entity.DataDictionaryEntity;
import cn.xshi.common.entity.UserInfoEntity;
import cn.xshi.log.client.service.LogsUtil;
import cn.xshi.oauth.service.OauthAccountService;
import cn.xshi.sys.model.SysUserInfo;
import cn.xshi.sys.service.SysUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
 * @Desc 员工信息
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/sysUserInfo")
@Api(value = "员工信息API",tags = "员工信息API",description = "员工信息API")
@Slf4j
public class SysUserInfoController extends BaseAction {

	@Resource
	SysUserInfoService sysUserinfoService;

	@Resource
	OauthAccountService oauthAccountService;

	@Resource
    CommonUtils commonUtils;

	@Resource
	LogsUtil logsUtil;

	/**
	* 查询员工信息列表并分页
	* @param baseSearch
	*/
	@PostMapping(value="/list")
	@Auth(value = "/sysUserInfo/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="查询员工信息列表并分页", notes="查询员工信息列表并分页")
	public BasePage<List<SysUserInfo>> getSysUserInfoListByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<SysUserInfo> sysUserInfoList = sysUserinfoService.getSysUserInfoListByCondition(condition);
		PageInfo<SysUserInfo> page = new PageInfo<SysUserInfo>(sysUserInfoList);
		return outPageBootStr(page,baseSearch);
	}
	
	/**
	 * 查询已删除用户列表并分页
	 * @param baseSearch
	 * @return
	 */
	@PostMapping(value="/deleted/list")
	@Auth(value = "/sysUserInfo/deleted/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="查询已删除用户列表并分页", notes="查询已删除用户列表并分页")
	public BasePage<List<SysUserInfo>> getSysUserInfoDeletedListByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<SysUserInfo> sysUserInfoList = sysUserinfoService.getSysUserInfoDeletedListByCondition(condition);
		PageInfo<SysUserInfo> page = new PageInfo<SysUserInfo>(sysUserInfoList);
		return outPageBootStr(page,baseSearch);
	}
	
	/**
	* 查询单个用户
	* @param id
	*/
	@GetMapping(value="/get/{id}")
	@Auth(value = "/sysUserInfo/get",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="查询单个用户", notes="查询单个用户")
	public BaseResult<SysUserInfo> getSysUserInfoById(@PathVariable("id")String id){
		SysUserInfo sysUserInfo = sysUserinfoService.getSysUserInfoById(id);
		return outDataStr(sysUserInfo);
	}
	
	/**
	* 添加
	* @param sysUserInfo
	*/
	@PostMapping(value="/add")
	@ApiOperation(value="创建单个用户", notes="创建单个用户")
	public BaseResult addSysUserInfo(@RequestBody SysUserInfo sysUserInfo){
		int i = 0;
		MD5 md5 = new MD5();
		if(null != sysUserInfo){
			if(StringUtil.isEmpty(sysUserInfo.getId())){
				throw new ExceptionUtil("账号id不存在");
			}
			sysUserInfo.setCreateId(getCurrentAccountId());
			sysUserInfo.setCreateTime(getDate());
			i= sysUserinfoService.addSysUserInfo(sysUserInfo);
			UserInfoEntity userInfoEntity = JsonUtil.fromFastJson(sysUserInfo, UserInfoEntity.class);
			new Thread(new SyncWorker(userInfoEntity)).start();
		}
		if(i>0){
			logsUtil.aBLogs("用户控制层", "添加", "添加用户成功");
			return outAudStr(true);
		}else{
			logsUtil.aBLogs("用户控制层", "添加", "添加用户失败");
			return outAudStr(false);
		}
	}
	
	/**
	* 修改
	* @param sysUserInfo
	*/
	@PutMapping(value="/update")
	@ApiOperation(value="编辑单个用户", notes="编辑单个用户")
	public BaseResult updateSysUserInfo(@RequestBody SysUserInfo sysUserInfo){
		int i = 0;
		if(null != sysUserInfo){

			sysUserInfo.setUpdateId(getCurrentAccountId());

			sysUserInfo.setUpdateTime(getDate());

			i= sysUserinfoService.updateSysUserInfo(sysUserInfo);

			UserInfoEntity userInfoEntity = JsonUtil.fromFastJson(sysUserInfo, UserInfoEntity.class);

			new Thread(new SyncWorker(userInfoEntity)).start();
		}
		if(i>0){
			logsUtil.aBLogs("用户控制层", "修改", "修改用户成功");
			return outAudStr(true);
		}else{
			logsUtil.aBLogs("用户控制层", "修改", "修改用户失败");
			return outAudStr(false);
		}
	}

	/**
	* 删除
	* @param id
	*/
	@DeleteMapping(value="/delete")
	@ApiOperation(value="删除用户", notes="删除用户")
	public BaseResult delSysUserInfo(String id){
		int i = 0;
		if(!StringUtil.isEmpty(id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id",id.split(","));
			i= sysUserinfoService.delSysUserInfo(condition);
		}
		if(i>0){
			logsUtil.aBLogs("用户控制层", "删除", "删除用户成功");
			return outAudStr(true);
		}else{
			logsUtil.aBLogs("用户控制层", "删除", "删除用户失败");
			return outAudStr(false);
		}
	}
	
	/**
	 * 获取名族数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/nation/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/nation/list")
	@ApiOperation(value=" 获取名族数据字典", notes=" 获取名族数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoNationList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("xt_userinfo_nation");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取性别数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/sex/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/sex/list")
	@ApiOperation(value=" 获取性别数据字典", notes=" 获取性别数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoSexList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("gender");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取文化程度数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/highestdegree/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/highestdegree/list")
	@ApiOperation(value=" 获取文化程度数据字典", notes=" 获取文化程度数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoHighestDegreeList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("xt_userinfo_highestDegree");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取工作年限数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/workyear/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/workyear/list")
	@ApiOperation(value=" 获取工作年限数据字典", notes=" 获取工作年限数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoWorkYearList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("xt_userinfo_workYear");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取是否已婚数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/ismarried/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/ismarried/list")
	@ApiOperation(value=" 获取是否已婚数据字典", notes=" 获取是否已婚数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoIsmarriedList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("xt_userinfo_ismarried");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 获取用户状态数据字典
	 * @param request
	 */
	@Auth(value = "/sysUserInfo/state/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/state/list")
	@ApiOperation(value=" 获取用户状态数据字典", notes=" 获取用户状态数据字典")
	public BaseResult<List<DataDictionaryEntity>> getSysUserInfoStateList(HttpServletRequest request){
		List<DataDictionaryEntity> dataDictionaryEntities = commonUtils.getSysDataDictionaryCache("xt_userinfo_state");
		return outComboDataStr(dataDictionaryEntities);
	}
	
	/**
	 * 判断用户名即登陆账号是否重复
	 * @param account
	 */
	@Auth(value = "/sysUserInfo/validate",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/validate/{account}")
	@ApiOperation(value=" 判断用户名即登陆账号是否重复", notes=" 判断用户名即登陆账号是否重复")
	public BaseResult validateUser(@PathVariable("account")String account){
		Map<String, Object> condition = new HashMap<String, Object>();
		if(!StringUtil.isEmpty(account)){
			condition.put("account", account);
			int i = sysUserinfoService.validateUser(condition);
			if(i > 0){
				return outAudStr(true,"1");
			}else{
				return outAudStr(true,"0");
			}
		}else{
			return outAudStr(false,"用户名参数未获取!验证失败!");
		}
	}
	
	/**
	* 恢复数据
	* @param id
	*/
	@GetMapping(value="/recover")
	@ApiOperation(value=" 恢复数据", notes=" 恢复数据")
	public BaseResult recoverSysUserInfo(String id){
		int i = 0;
		if(!StringUtil.isEmpty(id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id",id.split(","));
			i= sysUserinfoService.recoverSysUserInfo(condition);
		}
		if(i>0){
			logsUtil.aBLogs("用户控制层", "恢复用户", "恢复用户成功");
			return outAudStr(true);
		}else{
			logsUtil.aBLogs("用户控制层", "恢复用户", "恢复用户失败");
			return outAudStr(false);
		}
	}

	/**
	 * 全部用户
	 * @param request
	 * @return
	 */
	@Auth(value = "/sysUserInfo/chatting/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/chatting/list")
	@ApiOperation(value=" 全部用户", notes=" 全部用户")
	public BaseResult getChattingUserInfoList(HttpServletRequest request){
		Map<String, Object> condition = new HashMap<String, Object>();
		List<BaseTreeGridEntity> list = new ArrayList<BaseTreeGridEntity>();
		List<SysUserInfo> sysUserInfoList = sysUserinfoService.getSysUserInfoListByCondition(condition);
		for(int i = 0; i < sysUserInfoList.size(); i++){
			SysUserInfo sysUserInfo = sysUserInfoList.get(i);
			BaseTreeGridEntity BaseTreeGridEntity = new BaseTreeGridEntity();
			BaseTreeGridEntity.setId(sysUserInfo.getId());
			BaseTreeGridEntity.setPid("0");
			BaseTreeGridEntity.setText(sysUserInfo.getName());
			BaseTreeGridEntity.setContent("");
			BaseTreeGridEntity.setLeaf(true);
			BaseTreeGridEntity.setIcon("/deng/images/icons/employee_manager.png");
			list.add(BaseTreeGridEntity);
		}
		BaseTreeGridEntity baseTreeGridEntity = new BaseTreeGridEntity();
		List<BaseTreeGridEntity> baseTreeGridEntityList = baseTreeGridEntity.buildTree(list,"0");
		String json = JsonUtil.toFastJson(baseTreeGridEntityList);
		return outStr(json);
	}
	
	/**
	 * 根据各种情况查找集合不分页（流程设计器中处理人 发起人 发起人组等使用）
	 * @param id
	 * @return
	 */
	@Auth(value = "/sysUserInfo/lc/list/userId",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@GetMapping(value="/lc/list/{id}")
	@ApiOperation(value=" 根据各种情况查找集合不分页", notes=" 根据各种情况查找集合不分页")
	public BaseResult<List<SysUserInfo>> getSysUserInfoList(@PathVariable("id")String id){
		List<SysUserInfo> list = new ArrayList<SysUserInfo>();
		if(!StringUtil.isEmpty(id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("id", id.split(","));
			list = sysUserinfoService.getSysUserInfoList(condition);
		}
		return  outItemsStr(list);
	}
	
	/**
	* myinfo
	*/
	@GetMapping(value="/myinfo")
	@Auth(value = "/sysUserInfo/myinfo",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@ApiOperation(value=" 当前用户信息", notes=" 当前用户信息")
	public BaseResult myInfo(){
		return outDataStr(getCurrentAccountInfo());
	}
	
	/**
	 * 流程模块使用（查找用户）
	 * @param baseSearch
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@PostMapping(value="/lc/list")
	@Auth(value = "/sysUserInfo/lc/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@ApiOperation(value=" 流程模块使用", notes=" 流程模块使用")
	public BasePage<List<SysUserInfo>> getSysUserInfoListForLcByCondition(@RequestBody(required=true)BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		List<SysUserInfo> sysUserInfoList = sysUserinfoService.getSysUserInfoListByCondition(condition);
		PageInfo<SysUserInfo> page = new PageInfo<SysUserInfo>(sysUserInfoList);
		return outPageStr(page,baseSearch);
	}

	/**
	 * 同步至授权中心
	 * @param userInfoEntity
	 */
	@PostMapping(value="/syncOauth")
	@ApiOperation(value="同步至授权中心", notes="同步至授权中心")
	public BaseResult syncOauth(@RequestBody UserInfoEntity userInfoEntity){
		BaseResult baseResult = new BaseResult();
		baseResult.setSuccess(false);
		if(null != userInfoEntity){
			if(StringUtil.isEmpty(userInfoEntity.getId())){
				baseResult.setMessage("未能获取到用户id");
				return baseResult;
			}
			Map<String,Object> condition = new HashMap<>();
			condition.put("id", userInfoEntity.getId().split(","));
			List<SysUserInfo> sysUserInfoList = sysUserinfoService.getSysUserInfoList(condition);
			List<UserInfoEntity> userInfoEntities = JsonUtil.toFastList(sysUserInfoList, UserInfoEntity.class);
			if(!CollectionUtils.isEmpty(userInfoEntities)) {
				for (UserInfoEntity entity : userInfoEntities) {
					entity.setAccountTypeId(userInfoEntity.getAccountTypeId());
					entity.setSync(userInfoEntity.getSync());
				}
				baseResult = oauthAccountService.sync(userInfoEntities);
			}
		}
		if(baseResult.getSuccess()){
			logsUtil.aBLogs("用户控制层", "同步至授权中心", "同步至授权中心成功");
			return baseResult;
		}else{
			logsUtil.aBLogs("用户控制层", "同步至授权中心", "同步至授权中心失败");
			return baseResult;
		}
	}

	/**
	 * 查询员工信息列表
	 * @param userinfoEntity
	 */
	@Auth(value = "/sysUserInfo/users",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
	@PostMapping(value="/users")
	@ApiOperation(value="查询员工信息列表", notes="查询员工信息列表")
	public BaseResult<List<SysUserInfo>> getUsers(@RequestBody UserInfoEntity userInfoEntity){
		if(StringUtil.isEmpty(userInfoEntity.getId())){
			return new BaseResult();
		}
		Map<String, Object> condition = new HashMap<>();
		condition.put("id",userInfoEntity.getId().split(","));
		List<SysUserInfo> userInfoList = sysUserinfoService.getSysUserInfoList(condition);
		return new BaseResult(userInfoList);
	}

	/**
	 * 上传头像
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/pic/upload")
	@Auth(value = "/sysUserInfo/pic/upload",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="上传头像", notes="上传头像")
	public BaseResult uploadMyPic(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//转型为MultipartHttpRequest：
		MultiValueMap<String, MultipartFile> multipartFileMultiValueMap =  multipartRequest.getMultiFileMap();//获取所有文件
		MultipartFile multipartFile = multipartRequest.getFile("userPicFile");//获取指定文件即前端file框name标签
		String account = getCurrentAccount();
		if(!StringUtil.isEmpty(account)){
			SysUserInfo sysUserInfo = sysUserinfoService.getSysUserInfoByUserName(account);
			String pic = null;
			if(null != multipartFile && null != sysUserInfo){
				try {
					pic = Base64Util.toBase64(multipartFile.getBytes());
					sysUserInfo.setImage(pic);
				}catch (Exception e){
					log.error(e.getMessage());
				}
				int i = sysUserinfoService.updateSysUserInfo(sysUserInfo);
				if(i>0){
					return BaseResult.success(sysUserInfo);
				}
			}
		}
		return BaseResult.fail();
	}

	/**
	 * 查询单个用户头像
	 * @param userName
	 */
	@GetMapping(value="/pic/{userName}")
	@Auth(value = "/sysUserInfo/pic/get",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@ApiOperation(value="查询单个用户头像", notes="查询单个用户头像")
	public BaseResult<SysUserInfo> getSysUserInfoPicById(@PathVariable("userName")String userName){
		SysUserInfo sysUserInfo = sysUserinfoService.getSysUserInfoByUserName(userName);
		return BaseResult.success(sysUserInfo);
	}

	/**
	 * 根据账号查找单个用户信息
	 * @param account
	 */
	@ApiOperation(value="根据账号查找单个用户信息", notes="根据账号查找单个用户信息")
	@Auth(value = "/sysUserInfo/single",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
	@GetMapping(value="/single/{account}")
	public BaseResult<SysUserInfo> getSingleOauthAccount(@PathVariable("account")String account){
		if(StringUtil.isEmpty(account)){
			return BaseResult.success();
		}
		SysUserInfo sysUserInfo = sysUserinfoService.getSysUserInfoByUserName(account);
		return outDataStr(sysUserInfo);
	}

	/**
	 * 信息变更同步信息至授权中心
	 */
	class SyncWorker implements Runnable {

		UserInfoEntity userInfoEntity;

		/**
		 *
		 */
		public SyncWorker(){

		}

		/**
		 *
		 * @param userInfoEntity
		 */
		public SyncWorker(UserInfoEntity userInfoEntity){
			this.userInfoEntity = userInfoEntity;
		}

		/**
		 *
		 */
		public void run() {
			if(null != userInfoEntity){
				userInfoEntity.setSync(0);//不同步类型
				userInfoEntity.setAccountTypeId("");//设置类型为空
				List<UserInfoEntity> userInfoEntities = new ArrayList<>();
				userInfoEntities.add(userInfoEntity);
				oauthAccountService.sync(userInfoEntities);
			}
		}
	}
}
